#include "settingmanage.h"

SettingManage* SettingManage::m_instance = nullptr;

SettingManage::SettingManage(QObject *parent)
    :QObject(parent)
{
    // 确保路径中的中文也正确处理
    QString configPath = QString::fromUtf8("C:/Users/shafl/Desktop/IoTDeviceManage/src/config/config.ini");
    m_pSettings = new QSettings(configPath, QSettings::IniFormat, this);

    // 必须在创建QSettings后立即设置编码
    m_pSettings->setIniCodec(QTextCodec::codecForName("UTF-8"));
}

SettingManage::~SettingManage()
{
    delete m_pSettings;
}

void SettingManage::setValue(const QString &key, const QVariant &value)
{
    // 确保字符串值是UTF-8编码
    if (value.type() == QVariant::String) {
        QString str = value.toString();
        QByteArray utf8Data = str.toUtf8();
        m_pSettings->setValue(key, QString::fromUtf8(utf8Data));
    } else {
        m_pSettings->setValue(key, value);
    }
}

QVariant SettingManage::getValue(const QString &key, const QVariant &defaultValue) const
{
    QVariant value = m_pSettings->value(key, defaultValue);
    // 如果是字符串，确保正确解码
    if (value.type() == QVariant::String) {
        QString str = value.toString();
        return QVariant(QString::fromUtf8(str.toLocal8Bit()));
    }
    return value;
}

bool SettingManage::contains(const QString &key) const
{
    return m_pSettings->contains(key);
}

void SettingManage::remove(const QString &key)
{
    m_pSettings->remove(key);
}

void SettingManage::sync()
{
    m_pSettings->sync();
}
void SettingManage::writeBatchKeys(const QString &section, const QString &baseKey, const QVector<QString> &values) {

    m_pSettings->beginGroup(section); // 进入目标节

    // 先清除旧数据（可选，避免残留）
    int i = 1;
    while (m_pSettings->contains(QString("%1_%2").arg(baseKey).arg(i))) {
        m_pSettings->remove(QString("%1_%2").arg(baseKey).arg(i));
        i++;
    }

    // 写入新数据（带索引）
    for (int j = 0; j < values.size(); j++) {
        m_pSettings->setValue(QString("%1_%2").arg(baseKey).arg(j+1), values[j]);
    }

    m_pSettings->endGroup();
}

// 批量读取同一节的"相同键"（带索引）
QVector<QString> SettingManage::readBatchKeys(const QString &section, const QString &baseKey) {
    QVector<QString> values;
    m_pSettings->beginGroup(section);
    for(int i=0;i<50;i++){
        QString key = QString("%1_%2").arg(baseKey).arg(i);
        if (!m_pSettings->contains(key))
            continue;
        values.append(m_pSettings->value(key).toString());
    }
    m_pSettings->endGroup();
    return values;
}
QStringList SettingManage::getDistinctPrefixes(const QString &section, const QString &delimiter) {
    m_pSettings->beginGroup(section);
    QSettings::setDefaultFormat(QSettings::IniFormat);
    m_pSettings->setIniCodec("UTF-8");
    QStringList allKeys = m_pSettings->allKeys();
    QSet<QString> prefixSet; // 使用QSet自动去重
    // 遍历所有键，提取前缀
    foreach (const QString &key, allKeys) {
        // 按分隔符拆分键名
        qDebug()<<key;
        QStringList parts = key.split(delimiter, Qt::SkipEmptyParts);
        if (parts.size() >= 2) { // 确保至少有前缀和后缀两部分
            prefixSet.insert(parts.first()); // 收集前缀
        } else {
            // 处理无分隔符的键（如"singleKey"），根据需求决定是否视为前缀
            // prefixSet.insert(key); // 取消注释则将整个键作为前缀
        }
    }
    m_pSettings->endGroup();
    return prefixSet.values(); // 转换为列表返回
}

void SettingManage::addSingleConfigData( const QString &section, const QString &prefix, const QString &value) {
    if(prefix.isEmpty()||value.isEmpty()||section.isEmpty())
        return;
    m_pSettings->beginGroup(section);
    int index = 1;
    QString newKey = QString("%1%2").arg(prefix).arg(index);
    while(contains(newKey)){
        qDebug()<<"newKey:"<<newKey;
        index++;
        newKey = QString("%1%2").arg(prefix).arg(index);
    }

    m_pSettings->setValue(newKey, value);
    m_pSettings->endGroup();
}

int SettingManage::updateConfigValuesByPrefix(const QString &section, const QString &prefix, const QString &oldValue,
                              const QString &newValue) {
    m_pSettings->beginGroup(section);
    // 获取所有键
    QStringList allKeys = m_pSettings->allKeys();
    int count = 0;
    // 遍历所有键，筛选匹配前缀的键并修改值
    foreach (const QString &key, allKeys) {
        if (key.startsWith(prefix)&&m_pSettings->value(key).toString()==oldValue) {
            m_pSettings->setValue(key, newValue);
            count++;
        }
    }
    m_pSettings->endGroup();
    return count; // 返回修改的键值对数量
}
int SettingManage::deleteConfigValuesByPrefix(const QString &section, const QString &prefix, const QString &Value) {
    m_pSettings->beginGroup(section);
    // 获取所有键
    QStringList allKeys = m_pSettings->allKeys();
    int count = 0;
    // 遍历所有键，筛选匹配前缀的键并修改值
    foreach (const QString &key, allKeys) {
        if (key.startsWith(prefix)&&m_pSettings->value(key).toString()==Value) {
            m_pSettings->remove(key);
            count++;
        }
    }
    m_pSettings->endGroup();
    return count; // 返回修改的键值对数量
}
